import sys
import re
import os

re_receive_msg = re.compile("receive_(\\S+)\\s(.*)\\[\\s*(\\d*\\.?\\d*)\\s*s\\.\\s*\\]$")

def parse_message(message):
	m = re_receive_msg.match(message)
	if m is not None:
		fct = m.group(1)
		dat = m.group(2)
		tim = float( m.group(3) )
		return fct,dat,tim
	else: return message
	

def parse_line(line):
	sp = line.split("\t")
	if len(sp) < 4: return None
	timestamp = sp[0]
	logger = sp[1]
	log_type = sp[2]	
	message = sp[3]
	decoded_message = parse_message(message)
	return timestamp,logger,log_type,decoded_message

def parse(name):
	results = []
	f = file(name,"r")
	line = f.readline()
	while len(line) > 0:
		parse_result = parse_line(line[:-1])
		if parse_result is not None: 
			results.append( parse_result)
		line = f.readline()
	f.close()
	return results

def main(args):
	try:
		results = parse(args[0])
		by_fct_time = analyse_results(results)
		plotme(by_fct_time,args[0]+".out")
	except IndexError:
		print "Usage: %s input_file"% sys.argv[0]

def analyse_results(tab):
	print len(tab),"results"
	by_fct_time = dict()
	for timestamp,logger,log_type,decoded_message in tab:
		try:
			fct,dat,tim = decoded_message
			try: 
				by_fct_time[fct].append(tim)
			except KeyError: by_fct_time[fct] = [tim]
		except: pass
	return by_fct_time

def plotme(by_fct_time,outprefix):
	for k,v in by_fct_time.items():
		if k in ("query","overlay_add_handle"):
			f = file(outprefix+"."+k+".data","w")
			for xi in xrange(len(v)):
				print >>f,"%d\t%s"%(xi,str(v[xi]))
			f.close()
			f = file(outprefix+"."+k+".plot","w")
			print >>f,"set term png"	
			print >>f,"set output '%s'"% (outprefix+"."+k+".png")
			print >>f,"plot '%s' using 2 with lines"% (outprefix+"."+k+".data")
			f.close()
			os.system("gnuplot %s"%(outprefix+"."+k+".plot") )	
	

if __name__ == "__main__":
	main(sys.argv[1:])
